<html>
  <body>
    <h1> Maksim Rozentsveyg's Calculator </h1>
    <h3> SID 003 692 329 </h3>
    <h2> Input: </h2>
    <form method="get">
      <input type="text" name="expr">
      <input type="submit" value="Calculate">
    </form>
    <h2> Result: </h2>
    <p>
<?php

if ($_GET["expr"] != null)
{
  $input = $_GET["expr"];

  $validchars =   "/" .
                  "^[0-9\+\-*\/\.\s]+$". // Can only have nums, ops, and spaces
                  "/";
  $invalidchars = "/".
                  "([\.+*\/])\1".        // Can't have adjacent ops (except -)
                  "|".
                  "(\s+\.\s+)".          // Can't have a lone period
                  "|".
                  "(\.[+*\-\/])".          // Can't have a period next to an op
                  "/";

  preg_match($validchars, $input, $matchvalid, PREG_OFFSET_CAPTURE);
  preg_match($invalidchars, $input, $matchinvalid, PREG_OFFSET_CAPTURE);

  if (!empty($matchvalid) && empty($matchinvalid))
  {
   // echo $input . " is valid";
    $output = "";

    ob_start();
    eval('$output = ' . $input . ';');

    if (ob_get_clean() !== "") {
      echo "Invalid input expression " . $input . ".";
    }
    else { 
      echo $input . ' = ' . $output;
    }
  } else echo "Invalid input expression " . $input . ".";

}

?>
    </p>
  </body>
</html>

